﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ProjectVLIB_LAB01.DA
{
    class DataAccess
    {
        private string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\INET_CWIN\ProjectVLIB_LAB01\ProjectVLIB_LAB01\ProjectLAB.mdf;Integrated Security=True;User Instance=True";
        private SqlConnection sqlConn;
        private SqlCommand sqlComm;
        private SqlDataAdapter sqlAdap;


        /// <summary>
        /// Mở kết nối
        /// </summary>
        public void openConnect()
        {
            sqlConn.Dispose();
            sqlConn = new SqlConnection(strConn);
            if (sqlConn.State == ConnectionState.Closed)
                sqlConn.Open();
        }

        public void closeConnect()
        {
            if (sqlConn != null && sqlConn.State == ConnectionState.Open)
            {
                sqlConn.Close();
            }
        }


        public int getNumberData(string str)
        {
            openConnect();
            sqlComm = new SqlCommand(str, sqlConn);
            int count = int.Parse(sqlComm.ExecuteScalar().ToString());
            closeConnect();
            return count;
        }

        public string getStringData(string str)
        {
            openConnect();
            sqlComm = new SqlCommand(str, sqlConn);
            string strReturn = sqlComm.ExecuteScalar().ToString();
            closeConnect();
            return strReturn;
        }

        public bool execute(string str)
        {
            openConnect();
            try
            {
                (new SqlCommand(str, sqlConn)).ExecuteNonQuery();
                closeConnect();
                return true;
            }
            catch
            {
                closeConnect();
            }
            return false;
            
        }

    }
}
